package com.xwder.netty.websocket;

import cn.hutool.core.date.DateUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * TextWebSocketFrame 类型，表示一个文本帧(frame)
 *
 * @author xwder
 * @date 2021/3/24 09:39
 **/
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(MyTextWebSocketFrameHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        logger.info("服务器端收到消息:{}", msg.text());
        // 回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间-" + DateUtil.formatDateTime(new Date()) + "-" + msg.text()));
    }

    /**
     * 当web客户端连接后， 触发方法
     *
     * @param ctx
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        logger.info("服务器端 handlerAdded 被调用，LongText:{},shortText:{}", channel.id().asLongText(), channel.id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        logger.info("服务器端 handlerRemoved 被调用，LongText:{},shortText:{}", channel.id().asLongText(), channel.id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.info("服务器端 发生异常", cause);
        ctx.close();
    }
}
